//
//  SingleTablePicker.swift
//  Game
//
//  Created by woniu on 2025/8/28.
//

import Foundation
import UIKit

class SingleTablePicker: UIView {
    
    public var onSelectedRowBlock: ((_ index: Int,_ value:String)->())?
    public var titleLab:UILabel!
    private var tableView:UITableView!
    private var dataArray:[String] = []
    private var defaultSelectRowTitle:String?
    
    class func view()->SingleTablePicker{
        return SingleTablePicker()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    private func setupUI() {
        self.backgroundColor = .white
        titleLab = UILabel()
        titleLab.text = "请选择类型"
        titleLab.textAlignment = .center
        titleLab.font = UIFont.systemFont(ofSize: Utils.isPad() ? 25 : 16)
        titleLab.textColor = .black
        self.addSubview(titleLab)
        
        tableView = UITableView(frame:.zero, style: .plain)
        tableView.frame = .zero
        tableView.backgroundColor = Colors.bgColor
        tableView.estimatedRowHeight = UITableView.automaticDimension
        tableView.estimatedSectionFooterHeight = 0
        tableView.estimatedSectionHeaderHeight = 0
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.keyboardDismissMode = .onDrag
        tableView.register(CommonTitleCell.self, forCellReuseIdentifier:"CommonTitleCell")
        tableView.delegate = self
        tableView.dataSource = self
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        tableView.register(CommonTitleCell.self, forCellReuseIdentifier:"CommonTitleCell")
        tableView.backgroundColor = .white
        tableView.delegate = self
        tableView.dataSource = self
        self.addSubview(tableView)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        titleLab.frame = CGRect(x: 0, y: 15, width: self.width, height: 25)
        tableView.frame = CGRect(x: 10, y: titleLab.frame.maxY+15, width: self.width-20, height: self.height-titleLab.frame.maxY-10)
    }
    
    private func update(dataArray:[String]){
        self.dataArray = dataArray
        tableView.reloadData()
    }
    
    @objc func onDismiss(sender:UIButton) {
        hidden()
    }
}

extension SingleTablePicker:UITableViewDataSource,UITableViewDelegate{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier:"CommonTitleCell", for: indexPath) as! CommonTitleCell
        let title = dataArray[indexPath.row]
        cell.titleLab.text = title
        if let selectedRowTitle = self.defaultSelectRowTitle,title == selectedRowTitle{
            cell.bgView.backgroundColor = Colors.blue.withAlphaComponent(0.3)
        }else{
            cell.bgView.backgroundColor = .white
        }
        return cell
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return Utils.isPad() ? 60 : 44
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        hidden()
        onSelectedRowBlock?(indexPath.row,dataArray[indexPath.row])
    }
}


extension SingleTablePicker {
    
    ///隐藏
    public func hidden() {
        self.superview?.removeFromSuperview()
    }
    
    ///
    public func show(dataArray:[String],pickerW:CGFloat,defaultSelectRowTitle:String? = nil) {
        self.defaultSelectRowTitle = defaultSelectRowTitle
        self.update(dataArray: dataArray)
        ///兼容低版本手机，可能获取keyWindow失败??
        let showBGView:UIView? = MyNavigator.getWindow() ?? MyNavigator.getTopVC()?.view
        let itemH:CGFloat = Utils.isPad() ? 60 : 44
        let pickerH:CGFloat = min(kScreenH-90, CGFloat(dataArray.count) * itemH + 100)
        
        if let window = showBGView{
            let bgView = UIButton(type: .custom)
            bgView.addTarget(self, action: #selector(onDismiss(sender:)), for: .touchUpInside)
            bgView.backgroundColor = UIColor.black.withAlphaComponent(0.7)
            bgView.frame = window.bounds
            window.addSubview(bgView)
            self.frame = CGRect(x: (kScreenW-pickerW)*0.5, y:(kScreenH-pickerH)*0.5, width:pickerW, height:pickerH)
            bgView.addSubview(self)
            self.circular5()
        }
    }
}
